package dao

import (
	"context"
	"fmt"

	"inventory/internal/model"
)

type view struct {
	model.FullRemark
	ID int `json:"id"`
}

// BuildMaterialsRemarks 构造物料快照
func (d *Dao) BuildMaterialsRemarks(ctx context.Context, sgID uint32, materialIDs []uint64) (materialMap map[string]*model.FullRemark, err error) {
	materialMap = make(map[string]*model.FullRemark)
	if len(materialIDs) == 0 {
		return
	}
	var views []view
	err = d.TransContext(ctx).Raw(
		`
			SELECT 
			m.id,
            m.name,
			CONCAT(tt.code, '-', t.code, '-', m.code) as code, CONCAT(tt.name, '/', t.name) as type, 
			t.id as type_id,
			u1.name as unit,
			u2.name as storage_unit, 
			m.storage_ratio,
			u3.name as purchase_unit,
			m.purchase_ratio,
			m.p_store_id
			FROM inv_material as m 
			JOIN inv_material_type as t ON m.mt_id = t.id 
			JOIN inv_material_type as tt ON t.parent_id = tt.id 
            JOIN inv_unit as u1 ON u1.id = m.unit 
            JOIN inv_unit as u2 ON u2.id = m.storage_unit
            JOIN inv_unit as u3 ON u3.id = m.purchase_unit
			WHERE m.sg_id = ? and m.id in ?
			`, sgID, materialIDs).Scan(&views).Error
	if err != nil {
		err = d.processSqlError(err)
		return
	}
	for i, v := range views {
		materialMap[fmt.Sprintf("m-%d", v.ID)] = &views[i].FullRemark
	}
	return
}
